<?php

namespace App\Http\Resources;

use App\Notifications\CommentLiked;
use App\Notifications\CommentReplied;
use App\Notifications\TopicDeleted;
use App\Notifications\TopicLiked;
use App\Notifications\TopicReplied;
use App\Notifications\TopicRestored;
use App\Models\User;
use Illuminate\Http\Resources\Json\JsonResource;

class NotificationResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'type' => $this->type,
            'data' => $this->formatData($this->data),
            'created_at' => $this->created_at->format('Y-m-d H:i'),
            'read_at' => $this->read_at,
            'action' => $this->getAction($this),
        ];
    }

    private function getAction($notification)
    {
        $type = $notification->type;
        $action = '';
        switch ($type) {
            case TopicReplied::class:
                $action = '回复了你的帖子';
                break;
            case CommentReplied::class:
                $action = '回复了你的评论';
                break;
            case TopicLiked::class:
                $action = '点赞了你的帖子';
                break;
            case CommentLiked::class:
                $action = '点赞了你的评论';
                break;
            case TopicRestored::class:
                $action = '恢复了你的帖子';
                break;
            case TopicDeleted::class:
                $action = '删除了你的帖子';
                break;
            default:
                break;
        }
        return $action;
    }

    private function formatData($data)
    {
        if (empty($data['user_avatar'])) {
            $data['user_avatar'] = attachmentUrl(User::DEFAULT_AVATAR, 80);
        } else {
            $data['user_avatar'] = attachmentUrl($data['user_avatar'], 80);
        }
        return $data;
    }

}
